package com.zhenlong01.zhentest.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @date 2019-08-23 18:01
 */
public class AccessTokenUtil {
   public static String accessToken;
   public static final String APPID = "wx81558dd543f697f9";
   public static final String APPSECRET = "b9876f03cd4588c6917143c3866647ec";

    public static JSONObject findWebAccessToken(String code){
        return NetUtil.post("https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid="+APPID+"&secret="+APPSECRET+"&code="+code
                        +"&grant_type=authorization_code"
                ,"");
    }

    public static void findAccessToken(RedisTemplate<String,Object> redisTemplate) throws Exception{
        System.out.println("开始获得accesstoken");
        URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(),"utf-8")
        );

        String str;
        StringBuffer sb = new StringBuffer();
        while((str=br.readLine())!=null){
            sb.append(str);
        }

        JSONObject obj =  JSON.parseObject(sb.toString());
        accessToken = obj.getString("access_token");
        redisTemplate.opsForValue().set("access_token",accessToken,2, TimeUnit.HOURS);

        JSONObject obj2 =   NetUtil.post("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken
                +"&type=jsapi","");

        String jsapi_ticket = obj2.getString("ticket");
        redisTemplate.opsForValue().set("jsapi_ticket",jsapi_ticket,2, TimeUnit.HOURS);

    }


}
